package com.myjava.managesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.myjava.managesystem.common.Email;
import com.myjava.managesystem.common.R;
import com.myjava.managesystem.entity.User;
import com.myjava.managesystem.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public R<String> login(HttpServletRequest request, @RequestBody Map map){
        if(!((String)map.get("code")).equals(stringRedisTemplate.opsForValue().get(map.get("phone")+"code"))){
            return R.error("验证码错误");
        }
        else {
            stringRedisTemplate.delete(map.get("phone")+"code");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        User user = new User();
        user.setPhone((String) map.get("phone"));
        wrapper.eq(User::getPhone,user.getPhone());
        if(userService.getOne(wrapper)==null){
            userService.save(user);
        }
        wrapper.clear();
        wrapper.eq(User::getPhone,user.getPhone());
        request.getSession().setAttribute("user",userService.getOne(wrapper).getId());
        log.info("------------"+user.getId());
        return R.success("登陆成功");
    }

    @PostMapping("/sendMsg/{email}")
    public R<String> sendMsg(@PathVariable String email) throws Exception {
        Integer code = (int) (Math.random()*9000)+1000;
        Email.send(email, String.valueOf(code));
        stringRedisTemplate.opsForValue().set(email+"code", String.valueOf(code),180, TimeUnit.SECONDS);
        log.info("生成的验证码是:"+String.valueOf(code));
        return R.success("发送成功");
    }
}
